package com.tanhua.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.pojo.User;
import com.tanhua.pojo.UserInfo;
import com.tanhua.server.vo.SoundVo;
import com.tanhua.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Slf4j
public class SoundService {

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    @Value("${tanhua.default.sound.id}")
    private String sid;

    @Autowired
    private UserInfoService userInfoService;


    /**
     * 上传声音
     *
     * @param soundFile
     * @return
     */
    public Boolean saveSound(MultipartFile soundFile) {

        User user = UserThreadLocal.get();

        //如果今日次数为零则不允许存
        String remainingTimes = this.soundApi.getUploadRemainingTimes(user.getId());
        if (StrUtil.isEmpty(remainingTimes) && Convert.toInt(remainingTimes) <= 0) {
            return false;
        }

        Sound sound = new Sound();
        sound.setUserId(user.getId());

        try {
            //上传音频
            StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),
                    StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true), null);

            //设置视频url
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

            String soundId = this.soundApi.saveSound(sound);
            return StrUtil.isNotEmpty(soundId);
        } catch (Exception e) {
            log.error("声音上传失败！soundFile = " + sound.getSoundUrl(), e);
        }
        return false;
    }

    /**
     * 获取音频
     *
     * @return
     */
    public SoundVo getSound() {
        User user = UserThreadLocal.get();
        SoundVo soundVo = new SoundVo();

        String downloadRemainingTimes = this.soundApi.getDownloadRemainingTimes(user.getId());

        //由于前段根据次数进行判断,这里不做具体判断
        //if (Convert.toInt(downloadRemainingTimes) <= 0) {
        //    soundVo.setRemainingTimes(0);
        //    return soundVo;
        //}

        //推荐id列表
        List<String> soundId = StrUtil.split(sid, ',');

        //随机获取一个
        int i = RandomUtil.randomInt(1, soundId.size());

        //获取sound对象
        Sound sound = this.soundApi.getSound(Convert.toLong(soundId.get(i)), user.getId());

        //填充soundVo对象
        soundVo.setId(Convert.toInt(sound.getUserId()));
        soundVo.setSoundUrl(sound.getSoundUrl());
        soundVo.setRemainingTimes(Convert.toInt(downloadRemainingTimes));

        //从mysql数据库中查到头像等数据
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(sound.getUserId());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setGender(userInfo.getSex().toString().equals("男") ? "man" : "woman");
        soundVo.setAge(userInfo.getAge());
        soundVo.setNickname(userInfo.getNickName());

        return soundVo;
    }
}
